package com.xx.robot.service;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xx.robot.common.util.UserUtils;
import com.xx.robot.common.util.gocphttp.CqMessageUtil;
import com.xx.robot.common.util.mongo.MongoDbUtil;
import com.xx.robot.common.constant.CollectionNameEnum;
import com.xx.robot.thrid.NewsHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.IntStream;

/**
 * 新闻相关服务
 */
@Component
@Slf4j
public class NewsService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 获取60s新闻图片
     */
    public void world60s() {

        String result = NewsHttpUtil.world60sImg();
        if (!JSONUtil.isJson(result)) {
            log.error("更新失败");
            return;
        }

        JSONObject resultJson = JSONUtil.parseObj(result);
        if (!CharSequenceUtil.equals(resultJson.getStr("code"), "200")) {
            log.error("更新失败");
            return;
        }

        String url = resultJson.getStr("imageUrl");
        String message = "[CQ:image,file=" + url + ",url=" + url + "]";

        // 只发送没有关闭推送的群
        List<JSONObject> groups = MongoDbUtil.selectAll(JSONObject.class, CollectionNameEnum.JX3_SERVER.getCode());
        groups.stream().filter(o -> !CharSequenceUtil.equals("1", o.getStr("news")))
                .forEach(p -> CqMessageUtil.groupSend(p.getStr("_id"), message, "false"));
    }

    /**
     * 60 s新闻
     */
    public void world60sJson() {
        String result = NewsHttpUtil.world60sJson();
        if (!JSONUtil.isJson(result)) {
            log.error("更新失败");
            return;
        }

        JSONObject resultJson = JSONUtil.parseObj(result);
        log.info(result);
        if (!CharSequenceUtil.equals(resultJson.getStr("success"), "true")) {
            log.error("更新失败");
            return;
        }

        JSONArray list = resultJson.getJSONArray("data");

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(resultJson.getStr("name")).append("\n");
        stringBuilder.append("今天是：").append(DateUtil.today()).append("\t");
        stringBuilder.append("农历：").append(new ChineseDate(DateUtil.date())).append("\n");
        IntStream.range(0, list.size()).forEach(i -> stringBuilder.append(i + 1).append("：")
                .append(list.get(i)).append("\n"));


        // 只发送没有关闭推送的群
        List<JSONObject> groups = MongoDbUtil.selectAll(JSONObject.class, CollectionNameEnum.JX3_SERVER.getCode());
        groups.stream().filter(o -> !CharSequenceUtil.equals("1", o.getStr("news")))
                .forEach(p -> CqMessageUtil.groupSend(p.getStr("_id"), stringBuilder.toString()));


    }

    /**
     * 获取摸鱼图片
     */
    public void fishRemindImg() {

        String result = NewsHttpUtil.fishRemindImg();
        if (!JSONUtil.isJson(result)) {
            log.error("更新失败");
            return;
        }

        JSONObject resultJson = JSONUtil.parseObj(result);
        if (!CharSequenceUtil.equals(resultJson.getStr("success"), "true")) {
            log.error("更新失败");
            return;
        }

        String url = resultJson.getStr("url");
        String message = "[CQ:image,file=" + url + ",url=" + url + "]";

        // 只发送没有关闭推送的群
        List<JSONObject> groups = MongoDbUtil.selectAll(JSONObject.class, CollectionNameEnum.JX3_SERVER.getCode());
        groups.stream().filter(o -> !CharSequenceUtil.equals("1", o.getStr("news")))
                .forEach(p -> CqMessageUtil.groupSend(p.getStr("_id"), message, "false"));

    }

    /**
     * 摸鱼小助手
     */
    public void fishRemind() {
        String result = NewsHttpUtil.fishRemind();
        if (CharSequenceUtil.isBlank(result)) {
            log.error("获取失败");
            return;
        }

        String message = CharSequenceUtil.replace(result, "<br/>", "\n");
        // 只发送没有关闭推送的群
        List<JSONObject> groups = MongoDbUtil.selectAll(JSONObject.class, CollectionNameEnum.JX3_SERVER.getCode());
        groups.stream().filter(o -> !CharSequenceUtil.equals("1", o.getStr("fish_remind")))
                .forEach(p -> CqMessageUtil.groupSend(p.getStr("_id"), message));

    }


    /**
     * 改变新闻资讯是否通知状态
     *
     * @param groupId 群号
     * @param status  0取消/1开启
     * @param user    用户
     * @return
     */
    public void newsSwitch(String groupId, int status, String filedName, JSONObject user) {

        boolean roleFlag = UserUtils.isAdminAndManagerAndBot(user);
        if (!roleFlag) {
            CqMessageUtil.groupSend(groupId, "干嘛呢！干嘛呢！你是群主吗？别捣乱一边玩去。");
            return;
        }

        String info = "";
        if (status == 0) {
            //取消
            mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(groupId))
                    , new Update().set(filedName, status), CollectionNameEnum.JX3_SERVER.getCode());
            info = "开启成功";
        }
        if (status == 1) {
            //开启
            mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(groupId))
                    , new Update().set(filedName, status), CollectionNameEnum.JX3_SERVER.getCode());
            info = "关闭成功";
        }
        CqMessageUtil.groupSend(groupId, info);
    }
}
